﻿#region License

// Another free, open solution by folks who get it.
// Copyright © 2011 Business in Unison, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.IO;
using System.Text.RegularExpressions;

using Exortech.NetReflector;

using ThoughtWorks.CruiseControl.Core;
using ThoughtWorks.CruiseControl.Core.Util;

using ILabeler = ThoughtWorks.CruiseControl.Core.ILabeller; // spelling fail

namespace Patterns.CruiseControl.Labelers
{
	/// <summary>
	/// 	Labels CC.Net builds with a project's version, according to a designated
	/// 	assembly version info file and attribute.
	/// </summary>
	[ReflectorType("assemblyVersionLabeler")]
	public class AssemblyVersionLabeler : ILabeler
	{
		[ReflectorProperty("filePath")]
		public string FilePath { get; set; }

		[ReflectorProperty("versionAttribute")]
		public string AttributeName { get; set; }

		[ReflectorProperty("prefix", Required = false)]
		public string LabelPrefix { get; set; }

		[ReflectorProperty("suffix", Required = false)]
		public string LabelSuffix { get; set; }

		#region Implementation of ITask

		public void Run(IIntegrationResult result)
		{
			result.Label = Generate(result);
		}

		public string Generate(IIntegrationResult integrationResult)
		{
			Log.Debug("Generating assembly version info...");

			try
			{
				var versionPattern = new Regex(string.Format(@"{0}\(""(?<version>.*)""\)", AttributeName));
				if (!Path.IsPathRooted(FilePath)) FilePath = Path.Combine(integrationResult.WorkingDirectory, FilePath);
				using (var reader = new StreamReader(FilePath))
					return string.Format("{0}{1}{2}",
						LabelPrefix ?? string.Empty,
						versionPattern.Match(reader.ReadToEnd()).Groups["version"].Value,
						LabelSuffix ?? string.Empty);
			}
			catch (Exception ex)
			{
				Log.Error("An error occurred while attempting to generate assembly version info!");
				Log.Error(ex);
				throw;
			}
		}

		#endregion
	}
}